package com.server.shop.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.PostConstruct;

import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestParam;

import com.config.AppReturn;
import com.config.ConstDefine;
import com.config.ConstService;
import com.jfinal.plugin.activerecord.tx.TxConfig;
import com.jfinal.weixin.sdk.api.CardApi;
import com.server.pay.PayService;
import com.server.shop.ShopDao;
import com.server.shop.ShopService;
import com.server.userCenter.UserCenterDAO;
import com.util.IOUtil;
import com.util.StrKit;

@Component
public class ShopServiceImpl implements ShopService{

	@Autowired
	ShopDao shopDao;

	@Autowired
	ConstService constService;
	
	@Autowired
	UserCenterDAO ucDao;
	
	@Autowired
	PayService payService;
	
	//查询省市区
	@Override
	public List<Map<String, Object>> getCity(String id, String type) 
	{
		if(type.equals("1"))//省
		{
			return constService.provinceList;
		}else if(type.equals("2"))//市
		{
			return constService.cityList.get(id);
		}else if(type.equals("3"))//区
		{
			return shopDao.getArea(id);
		}
		
		return null;
	}
	//查询广告
	@Override
	@Cacheable("getBanner")
	public List<Map<String, Object>> getBanner(String classes) 
	{
		System.out.println("查询广告！");
		Map<String, Object> reqMap=new HashMap<String, Object>();
		if(StrKit.notBlank(classes))//按照分类查询
		{
//			reqMap.put("bannertype", "2");
			reqMap.put("classes", classes);
		}else//查询主页
		{
//			reqMap.put("bannertype", "1");
		}
		List<Map<String, Object>> list = shopDao.getBanner(reqMap);
		return list;
	}

	//查询消息
	@Override
	@Cacheable("getNotice")
	public List<Map<String, Object>> getNotice(String type) 
	{
		Map<String, Object> reqMap=new HashMap<String, Object>();
		List<Map<String, Object>> list = shopDao.getNotice(reqMap);
		
		return list;
	}
	
	//查询商品列表
	@Override
	public List<Map<String, Object>> getGoodsList(String name, String classid,String positionid,String iftop) 
	{
		Map<String, Object> reqMap=new HashMap<String, Object>();
		if(StrKit.notBlank(name))reqMap.put("name", name);
		if(StrKit.notBlank(classid))reqMap.put("classid", classid);
		if(StrKit.notBlank(positionid))reqMap.put("positionid", positionid);
		if(StrKit.notBlank(iftop))reqMap.put("iftop", iftop);
		List<Map<String, Object>> list = shopDao.getGoods(reqMap);
		
		return list;
	}

	//查询商品详情
	@Override
	public Map<String, Object> getGoodsDetail(Map<String, Object> user, String goodsid) 
	{
		//商品详情
		Map<String, Object> goods = shopDao.getGoodsDetail(goodsid);
		
		//规格列表
		List<Map<String, Object>> stockList = shopDao.getGoodsStock(goodsid);
		//封装JSON
		Map<String, Object> data = new HashMap<String, Object>();
		data.put("goods", goods);
		data.put("stocks", stockList);
		data.put("classid", goods.get("classid"));
		//判断如果规格只有一种，直接返回
		if(stockList!=null&&stockList.size()==1)
		{
			data.put("sid", stockList.get(0).get("id"));
		}
		
		
		return data;
	}

	//增加到购物车
	@Override
	public AppReturn addCar(Map<String, Object> user, String goodsid,String stockid, String goodsnum) 
	{
		//校验数量
		if(StrKit.isBlank(goodsnum)|| Integer.parseInt(goodsnum)<1)return new AppReturn("05", "请输入正确的商品数量");
		String id=IOUtil.getId();
		String userid=(String)user.get("id");
		shopDao.addShopCar(id,userid , goodsid, stockid, Integer.parseInt(goodsnum));
		//查询该条信息的ID
		Map<String, Object> carDetail = shopDao.getShopCarDetail(userid, goodsid, stockid);
		id=(String)carDetail.get("id");
		JSONObject data = new JSONObject();
		data.put("id", id);
		return new AppReturn("00","",data);
	}

	//直接购买商品
	@Override
	public AppReturn buyGoods(Map<String, Object> user, String goodsid,String stockid, String num,String addrid) 
	{
		//生成订单
		return doCreateList(user,goodsid, stockid, num, addrid);
	}
	
	//结算购物车中的商品
	@Override
	public AppReturn buyCarGoods(Map<String, Object> user, String ids,String addrid) 
	{
		//处理购物车ID
		String carIds="(";
		String[] caridArr=ids.split("#");
		for(int i=0;i<caridArr.length;i++)
		{
			if(i!=0)carIds=carIds+",";
			carIds=carIds+"'"+caridArr[i]+"'";
		}
		carIds=carIds+")";
		System.out.println("carids :"+carIds);
		
		//通过购物车ID，查询商品
		List<Map<String, Object>> list = shopDao.getGoodsIDByCarids(carIds);
		if(list==null||list.size()<1)return new AppReturn("05","请选择要结算得商品！");
		String goodsids = "";
		String stockids = "";
		String nums = "";
		for(int i=0;i<list.size();i++)
		{
			Map<String, Object> data = list.get(i);
			if(i!=0){
				goodsids=goodsids+"#";
				stockids=stockids+"#";
				nums=nums+"#";
			}
			goodsids=goodsids + data.get("goodsid");
			stockids=stockids + data.get("stockid");
			nums=nums + (Integer)data.get("num");
		}
		
		//删除已购买商品
		shopDao.delCarIn(carIds);
		
		return doCreateList(user, goodsids, stockids, nums, addrid);
	}
	//更新购物车中商品数量
	@Override
	public AppReturn upCar(Map<String, Object> user, String id, String num) 
	{
		//验证数量
		if(StrKit.isBlank(num)||Integer.parseInt(num)<1)return new AppReturn("05", "商品数量有误！");
		//验证购物车归属
		Map<String, Object> carDetail=shopDao.getCarDetail(id);
		if(carDetail==null||carDetail.get("userid")==null||!carDetail.get("userid").equals(user.get("id").toString()))return new AppReturn("06", "商品信息有误！");
		//更新数量
		int res = shopDao.upCarNum(id, Integer.parseInt(num));
		
		return StrKit.int2ret(res);
	}
	
//	/**
//	 * 生成订单
//	 * @param user
//	 * @param goodsids 商品ID，多个中间用#分割
//	 * @param stockids 库存ID，多个中间用#分割
//	 * @param nums     商品数量，多个中间用#分割
//	 * @return
//	 */
//	public int createList1(Map<String, Object> user, String goodsids,String stockids, String nums,String addrid)
//	{
//		System.out.println("stocks : "+stockids);
//		int res = 0;
//		//计算金额
//		double amount = 0;//订单总金额
//		String[] stockidArr=stockids.split("#");
//		String[] goodsidArr=goodsids.split("#");
//		String[] numsArr=nums.split("#");
//		for(int i=0;i<stockidArr.length;i++)
//		{
//			int num = Integer.parseInt(numsArr[i]);
//			Map<String, Object> stockDetail=shopDao.getStockDetail(stockidArr[i]);
//			amount=amount+(Double)stockDetail.get("price")*num;
//		}
//		
//		
//		//插入订单记录
//		String id=IOUtil.getId();
//		shopDao.insList(id, user.get("id").toString(), amount, addrid);
//		
//		//插入订单商品记录
//		List<Map<String, Object>> goodsList = new ArrayList<Map<String,Object>>();
//		for(int i=0;i<goodsidArr.length;i++)
//		{
//			int num = Integer.parseInt(numsArr[i]);
//			Map<String, Object> stockDetail=shopDao.getStockDetail(stockidArr[i]);
//			amount=((Double)stockDetail.get("price"))*num;
//			Map<String, Object> goodsList_map=new HashMap<String, Object>();
//			goodsList_map.put("listid", id);
//			goodsList_map.put("goodsid", goodsidArr[i]);
//			goodsList_map.put("stockid", stockidArr[i]);
//			goodsList_map.put("userid", user.get("id").toString());
//			goodsList_map.put("num", num+"");
//			goodsList_map.put("amount", amount);
//			goodsList_map.put("ifreward", stockDetail.get("ifreward"));
//			goodsList.add(goodsList_map);
//		}
//		shopDao.insListGoods(goodsList);
//		res = 1;
//		return res;
//	}
//	//生成订单
//	@Override
//	public AppReturn createList(Map<String, Object> user, JSONObject goods) 
//	{
//		String addrid = goods.getString("addrid");
//		
//		JSONArray jsa = goods.getJSONArray("goods");
//		String[] stockidArr= new String[jsa.length()] ; 
//		String[] goodsidArr= new String[jsa.length()] ;
//		String[] numsArr= new String[jsa.length()] ;
//		for(int i=0;i<jsa.length();i++)
//		{
//			JSONObject goodsJson=(JSONObject) jsa.get(i);
//			stockidArr[i]=goodsJson.getString("stockid");
//			goodsidArr[i]=goodsJson.getString("goodsid");
//			numsArr[i]=goodsJson.getString("num");
//			
//		}
//		return doCreateList(user, stockidArr, goodsidArr, numsArr, addrid);
//	}	
	
	/**
	 * 处理生成订单实际操作
	 * @param user
	 * @param stockidArr
	 * @param goodsidArr
	 * @param numsArr
	 * @return
	 */
	public AppReturn doCreateList(Map<String, Object> user, String goodsids,String stockids, String nums,String addrid)
	{

		String[] stockidArr = stockids.split("#");
		String[] numsArr = nums.split("#");
		String[] goodsidArr = goodsids.split("#");
		
		String delGoodsId="(";//要删除的购物车商品
		//计算金额
		double amount = 0;//订单总金额
		double amount_reward = 0;//需要计算优惠得总金额
		int ifstock=1;//库存是否足够，1=够。0=不够
		String ifreward_list="1";//判断是否为返利订单
		for(int i=0;i<stockidArr.length;i++)
		{
			int num = Integer.parseInt(numsArr[i]);
			Map<String, Object> stockDetail=shopDao.getStockDetail(stockidArr[i]);
			//判断库存
			if(num>(Integer)stockDetail.get("stock"))
			{
				ifstock=0;
				break;
			}
			amount=amount+(Double)stockDetail.get("price")*num;
			if(stockDetail.get("ifreward").equals("1")){
				amount_reward=amount_reward+(Double)stockDetail.get("price")*num;//判断如果是返利商品。则增加金额
			}else{
				ifreward_list="0";//只要有一个商品是非返利得，订单改为非返利
			}
		}
		//判断库存
		if(ifstock==0)return new AppReturn("00", "库存不足！");
		
		//插入订单记录
		String id=IOUtil.getId();
		String goodstype="1";//商品类型
		
		//插入订单商品记录
		List<Map<String, Object>> goodsList = new ArrayList<Map<String,Object>>();
		for(int i=0;i<goodsidArr.length;i++)
		{
			int num = Integer.parseInt(numsArr[i]);
			Map<String, Object> stockDetail=shopDao.getStockDetail(stockidArr[i]);
			goodstype = (String)stockDetail.get("goodstype");
			double amountgoods=(Double)stockDetail.get("price")*num;
			Map<String, Object> goodsList_map=new HashMap<String, Object>();
			goodsList_map.put("listid", id);
			goodsList_map.put("goodsid", goodsidArr[i]);
			goodsList_map.put("stockid", stockidArr[i]);
			goodsList_map.put("userid", user.get("id").toString());
			goodsList_map.put("num", num+"");
			goodsList_map.put("amount", amountgoods);
			goodsList.add(goodsList_map);
			
			//封装要清空的商品ID
			if(i>0)delGoodsId=delGoodsId+",";
			delGoodsId=delGoodsId+goodsidArr[i];
		}

		shopDao.insList(id, user.get("id").toString(), amount,amount_reward, addrid,ifreward_list,goodstype);
		shopDao.insListGoods(goodsList);
		//删除购物车记录
		delGoodsId=delGoodsId+")";
		shopDao.delCarByGoodsId(delGoodsId,  user.get("id").toString());
		
		JSONObject data = new JSONObject();
		data.put("id", id);
		data.put("amount", amount);
		
		return new AppReturn("00","",data);
	}
	
	//查询我的购物车
	@Override
	public AppReturn getMyCar(Map<String, Object> user) 
	{
		List<Map<String, Object>> list = shopDao.getUserCar(user.get("id").toString());
		
		return StrKit.list2Appreturn(list);
	}
	//删除购物车中商品
	@Override
	public AppReturn delCar(Map<String, Object> user, String id) 
	{
		String delIds = IOUtil.getStrInByStr(id, "#");
		System.out.println("删除ID："+delIds);
		int res = shopDao.delCars(delIds);
		
		return StrKit.int2ret(res);
	}
	
	//获取邮费，总金额
	@Override
	public AppReturn getPostFee(Map<String, Object> user, JSONObject goods) 
	{
		String addrid = goods.getString("addrid");
		int res = 0;
		//计算金额
		double amount = 0;//订单总金额
		JSONArray jsa = goods.getJSONArray("goods");
//		String[] stockidArr=stockids.split("#");
//		String[] goodsidArr=goodsids.split("#");
//		String[] numsArr=nums.split("#");
		String[] stockidArr= new String[jsa.length()] ;
		String[] goodsidArr= new String[jsa.length()] ;
		String[] numsArr= new String[jsa.length()] ;
		for(int i=0;i<jsa.length();i++)
		{
			JSONObject goodsJson=(JSONObject) jsa.get(i);
			stockidArr[i]=goodsJson.getString("stockid");
			goodsidArr[i]=goodsJson.getString("goodsid");
			numsArr[i]=goodsJson.getString("num");
		}
		
		for(int i=0;i<stockidArr.length;i++)
		{
			int num = Integer.parseInt(numsArr[i]);
			Map<String, Object> stockDetail=shopDao.getStockDetail(stockidArr[i]);
			amount=amount+(Double)stockDetail.get("price")*num;
		}
		
		JSONObject data = new JSONObject();
		data.put("postFee", "0");
		data.put("listFee", amount+"");
		
		return new AppReturn("00", "", data);
	}
	
	//查询购物车中商品信息
	@Override
	public List<Map<String, Object>> getMyCarByIds(Map<String, Object> user, String ids) 
	{
		String userid = (String) user.get("id");
		String idsin = IOUtil.getStrInByStr(ids, "-");
		
		List<Map<String, Object>> goods = shopDao.getUserCarByID(userid, idsin);
		
		return goods;
	}
	//积分支付订单
	@Override
	@Transactional(rollbackFor = Exception.class)
	public AppReturn doPayPoint(Map<String, Object> user, String listid) 
	{
		//判断订单状态，以及归属
		Map<String, Object> list = ucDao.getListDetail(listid);
		if(list==null||!list.get("status").equals("1")||!list.get("userid").equals(user.get("id"))||!list.get("goodstype").equals("2"))return new AppReturn("01","订单信息错误！");
		//判断积分是否足够
		String userid = (String) user.get("id");
		double amount = (double) list.get("amount");//积分
		int amount_lq = (int) user.get("amount_lq");//用户积分
		if(amount_lq<amount)return new AppReturn("02","您的礼券不足！");
		//扣减积分,插入记录
		int res = ucDao.upUserAmount(userid, 0, 0, 0-amount);
		if(res>0){
			res=ucDao.insLQLog(IOUtil.getId(), userid, "2", (0-amount)+"", ConstDefine.COST_LQ, "", listid);
		}
		//更新订单、库存
		//更新订单状态
		list.put("status", "2");
		list.put("pay_type", "4");
		ucDao.upList(list);

		//扣减库存
		List<Map<String, Object>> listGoods = ucDao.getListGoods(listid);
		ucDao.deuGoodsStock(listGoods);
		//防止扣减多了，库存出现负数
		ucDao.upStock2zero();
		//更新已售商品数量
		ucDao.upGoodsSoldNum();		
		
		return StrKit.int2ret(res);
	}
	
	//执行预约
	@Override
	public AppReturn doShopJoin(Map<String, Object> user, String phone, String name, String addr,String goodsid,String dkpzurl) {
		String userid = (String) user.get("id");
		

		//判断是否已经有带申请，或者已经成功得记录
		List<Map<String, Object>> joinLog = shopDao.getJoinLog(userid, null, "('1','0')");
		if(joinLog!=null&&joinLog.size()>0)
		{
			return new AppReturn("01", "请勿重复申请！");
		}
		//插入记录
		Map<String, Object> reqMap = new HashMap<String, Object>();
		reqMap.put("phone", phone);
		reqMap.put("name", name);
		reqMap.put("addr", addr);
		reqMap.put("goodsid", goodsid);
		reqMap.put("userid", userid);
		reqMap.put("dkpzurl", dkpzurl);
		
		int res = shopDao.insShopJoin(reqMap);
		
		//获取ID，后期支付时使用
//		System.out.println("id:::"+reqMap.get("id").toString());
//		JSONObject data = new JSONObject();
//		data.put("id", reqMap.get("id"));
//		ret.setData(data);

		AppReturn ret = StrKit.int2ret(res);
		return ret;
	}
	//查询活动列表
	@Override
	public List<Map<String, Object>> getActivity(Map<String, Object> user) {
		
		List<Map<String, Object>> list = shopDao.getActivity();
		
		return list;
	}
	//活动页面详情
	@Override
	public Map<String, Object> getActivityDetail(Map<String, Object> user, String id) 
	{
		Map<String, Object> map = shopDao.getActivityDetail(id);
		
		return map;
	}
	//知识列表
	@Override
	public List<Map<String, Object>> getKnowledge(Map<String, Object> user) {
		List<Map<String, Object>> list = shopDao.getKnowledge();
		
		return list;
	}
	//知识详情
	@Override
	public Map<String, Object> getKnowledgeDetail(Map<String, Object> user, String id) {
		Map<String, Object> map = shopDao.getKnowledgeDetail(id);
		
		return map;
	}
	
	
}
